<template>
    <label>
        <span>
            <input v-if="group" :value="label" v-model="model" type="checkbox" :disabled="disabled" :checked="currentValue"
                   @change="change">
            <input v-else type="checkbox" :value="label" :disabled="disabled" :checked="currentValue" @change="change">
        </span>
        {{label}}
    </label>
</template>

<script>
  import Emitter from '../../mixins/emitter.js'
  import { findComponentUpward } from "../../utils/assist"

  export default {
    name: 'iCheckbox',
    mixins: [Emitter],
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      label: {
        type: [String, Number, Boolean]
      },
      value: {
        type: [String, Number, Boolean],
        default: false
      },
      trueValue: {
        type: [String, Number, Boolean],
        default: true
      },
      falseValue: {
        type: [String, Number, Boolean],
        default: false
      }
    },
    data() {
      return {
        currentValue: this.value,
        model: [],
        group: false,
        parent: null
      }
    },
    mounted() {
      this.parent = findComponentUpward(this, 'iCheckboxGroup')
      this.parent && (this.group = true)

      if (this.group) {
        this.parent.updateModel(true)
      } else {
        this.updateModel()
      }

    },
    methods: {
      change(event) {
        if (this.disabled) {
          return false
        }

        const checked = event.target.checked
        this.currentValue = checked

        const value = checked ? this.trueValue : this.falseValue  // currentValue仍然是true和false，给elem用，根据判断，返回
        this.$emit('input', value)

        // group模式下，直接对group做change
        if(this.group) {
          this.parent.change(this.model)
        } else {
          this.$emit('on-change', value)
          this.dispatch('iFormItem', 'on-form-change', value)
        }

      },
      updateModel() {
        this.currentValue = this.value === this.trueValue
      }
    },
    watch: {
      // 外面传入的prop，如果另行使用需要watch，直接赋值给elem除非不做变动，否则还是要单独再引用一次
      value(val) {
        if (val === this.trueValue || val === this.falseValue) {
          this.updateModel()
        } else {
          throw 'Value should be trueValue or falseValue'
        }
      }
    }
  }
</script>
